<?php

namespace app\admin\controller\buchang;

use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Diaodu extends Backend
{

    /**
     * Diaodu模型对象
     * @var \app\admin\model\buchang\Diaodu
     */
    protected $model = null;
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\buchang\Diaodu;
        $this->view->assign("statusList", $this->model->getStatusList());
        $site = Config::get('site');
        $this->view->assign('chexing', $site['chexing']);
        $this->view->assign('xingzhi', $site['xingzhi']);
        $this->view->assign('task', $site['task_list']);

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function diaodu($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['yw_class_text'] = Db::name('zuzhi')->where('id', $row['yw_class'])->value('name');
            $this->view->assign('row', $row);
            $res = Db::name('list_one')->where('tong_number', $row['tong_number'])
                ->field('id,ids,yw_come,yw_class,yw_peo,yw_peo_phone,yw_belonger,yw_handle,yw_join_time,yw_enter_peo,yw_hetongpeo,yw_hetong_time,yw_finance_peo,yw_shenhe_time,tong_storage,tong_number,tong_document,give_company,give_starttime,give_endtime,car_num,car_is_new,car_num_kind,haocolor,car_province,car_check,car_check_res,car_owner,car_card_kind,car_card,car_relation,car_address,car_vin,car_engine,car_factory_num,car_register,car_age,car_issue_time,car_is_transfer,car_buy,car_reall,car_use_nature,car_leixing,car_kind,car_carry_peo,car_carry_quality,car_curb_weight,car_displacement,car_power,car_lastyear,car_rank,plan_strattime,plan_endtime,main_name,main_money,main_standard,main_discount,main_submit,main_franchise,main_disan,main_santong,main_biao,main_zhe,main_yingjiao,main_ji,dao_name,dao_tong,dao_biao,dao_zhe,dao_ying,dao_ji,siji,siji_tong,siji_biao,siji_zhe,siji_ying,siji_ji,chengke,ck_money,chengke_zuo,ck_tong,ck_biao,ck_zhe,ck_ying,ck_ji,buji,bu_tong,bu_biao,bu_zhe,bu_ying,bu_buji,ziran,zi_tong,zi_biao,zi_zhe,zi_ying,zi_buji,fdjsunshi,fdj_tong,fdj_biao,fdj_zhe,fdj_ying,fdj_buji,zdxiuli,zd_tong,zd_biao,zd_zhe,zd_ying,zd_buji,huowu,hw_tong,hw_biao,hw_zhe,hw_ying,hw_buji,boli,bl_tong,bl_biao,bl_zhe,bl_ying,bl_buji,main_sum,main_sumdiscount,main_free,main_netrate,main_netcost,ginseng_name,ginseng_kind,ginseng_card,ginseng_phone,ginseng_email,ginseng_address,learned_name,learned_kind,learned_num,learned_phone,learned_email,learned_address,resolvent,special,invoice_kind,invoice_name,invoice_num,invoice_bank,bank_address,invoice_phone,beizhu,zhanghao,file,file_name,shuoming,shenhe_time,shenhe_peo,shenhe_yijian,status,statuss,pigai_type,pigai_numz,pigai_nump,pigai_piwen,pigai_ctime,pigai_pddzh,main_tongchoufee_heji,main_xiaoguan_bili,main_xiaoguan,main_yunying_bili,main_yunying,main_tongchoujingfee_heji,dong_fee,ncd,give_number,kehu_sumdiscount,chexing,chexing_ci,feiyong,jiafei,jiaofei,jiaofei_price,jiaofei_time,jiaofei_type,trade_no,out_trade_no,type,lururen,lururen_id,feiyong_type,feiyong_qita,jiafei_type,shui_lv1,shui_lv,ziran_c,fd_c,zd_c,huowu_c,boli_c,urls1,urls2,tcxm,status_type,qianzi_status,pdf,chezhu,tk_type,bjt,gs_type,zq_id,dianwang,dw_tong,dw_biao,dw_zhe,dw_ying,dw_ji')
                ->find();
            $res['yw_class_text'] = $row['yw_class_text'];
            $this->view->assign('res', $res);
            $zuzhi = Db::name('zuzhi')->where('id', 1)->field('id,name')->select();
            $this->assign('zuzhi', $zuzhi);
            $log = Db::name('diaodu_log')->where('bid', $ids)->order('id desc')->field('create_time,remark,user_name,task,task_num')->select();
            $this->assign('diaodu_log', $log);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if (!isset($params['chakan_group']) || empty($params['chakan_group'])) $this->error('请选择查勘机构');
        if (!isset($params['chakan_ren']) || empty($params['chakan_ren'])) $this->error('请选择查勘人');
        if (!isset($params['chakan_user_id']) || empty($params['chakan_user_id'])) $this->error('请选择查勘人');

        $post = $this->request->post();
        $gai_task = $post['gai_task'];
        $gai_task_num = $post['gai_task_num'];
        $params['beizhu'] = trim($params['beizhu']);
        if (empty($gai_task)) $this->error('请选择委派任务');

        $task_list = Config::get('site.task_list');//任务列表
        foreach ($gai_task as $val) {
            if (!isset($task_list[$val])) continue;
            $task[] = $task_list[$val];
        }
        $task_num = [];
        $index = 0;
        foreach ($task_list as $k => $v) {
            if (in_array($k, $gai_task)) {
                $task_num[] = $gai_task_num[$index];
            }
            $index++;
        }
        $task = implode('、', $task);
        $admin = $this->auth->getUserInfo();
        $msg = "查勘机构：%s,  查勘人：%s,  任务：%s,  备注：%s";
        $log['create_time'] = time();
        $log['bid'] = $ids;
        $log['userid'] = $admin['id'];
        $log['user_name'] = $admin['username'];
        $log['chakan_user_id'] = $params['chakan_user_id'];
        $log['task'] = implode(',', $gai_task);
        $log['task_num'] = implode(',', $task_num);
        $chakan_group_name = Db::name('zuzhi')->where('id', $params['chakan_group'])->value('name');
        $log['remark'] = sprintf($msg, $chakan_group_name, $params['chakan_ren'], $task, $params['beizhu']);
        foreach ($gai_task as $index => $item) {
            $params['task_' . $item] = $task_num[$index];
            if ($item == 1) {
                // 本车定损
            } elseif ($item == 2) {
                // 三者财物损失定损
                $count = Db::name("scwusun")->where("bid", $ids)->count();
                if ($task_num[$index] > $count) {
                    // 增加条数
                    for ($i = $count; $i < $task_num[$index]; $i++) {
                        $i_data = array();
                        $i_data['bid'] = $ids;
                        $i_data['xuhao'] = $i + 1;
                        Db::name("scwusun")->insert($i_data);
                    }
                } elseif ($task_num[$index] < $count) {
                    // 尝试减少条数
                    for ($i = $task_num[$index]; $i < $count; $i++) {
                        $d = Db::name("scwusun")->where("bid", $ids)->order("id desc")->find();
                        if (empty($d)) {
                            continue;
                        } else {
                            if (empty($d['name'])) {
                                Db::name("scwusun")->where("id", $d['id'])->delete();
                            } else {
                                continue;
                            }
                        }
                    }
                }
            } elseif ($item == 3) {
                // 三者车损失定损
                $count = Db::name("sanche")->where("bid", $ids)->count();
                if ($task_num[$index] > $count) {
                    // 增加条数
                    for ($i = $count; $i < $task_num[$index]; $i++) {
                        $i_data = array();
                        $i_data['bid'] = $ids;
                        $i_data['xuhao'] = $i + 1;
                        Db::name("sanche")->insert($i_data);
                    }
                } elseif ($task_num[$index] < $count) {
                    // 尝试减少条数
                    for ($i = $task_num[$index]; $i < $count; $i++) {
                        $d = Db::name("sanche")->where("bid", $ids)->order("id desc")->find();
                        if (empty($d)) {
                            continue;
                        } else {
                            if (empty($d['name'])) {
                                Db::name("sanche")->where("id", $d['id'])->delete();
                            } else {
                                continue;
                            }
                        }
                    }
                }
            } elseif ($item == 4) {
                // 本车人伤
                $count = Db::name("benren")->where("bid", $ids)->count();
                if ($task_num[$index] > $count) {
                    // 增加条数
                    for ($i = $count; $i < $task_num[$index]; $i++) {
                        $i_data = array();
                        $i_data['bid'] = $ids;
                        $i_data['xuhao'] = $i + 1;
                        Db::name("benren")->insert($i_data);
                    }
                } elseif ($task_num[$index] < $count) {
                    // 尝试减少条数
                    for ($i = $task_num[$index]; $i < $count; $i++) {
                        $d = Db::name("benren")->where("bid", $ids)->order("id desc")->find();
                        if (empty($d)) {
                            continue;
                        } else {
                            if (empty($d['name'])) {
                                Db::name("benren")->where("id", $d['id'])->delete();
                            } else {
                                continue;
                            }
                        }
                    }
                }
            } elseif ($item == 5) {
                // 三者人伤
                $count = Db::name("sanren")->where("bid", $ids)->count();
                if ($task_num[$index] > $count) {
                    // 增加条数
                    for ($i = $count; $i < $task_num[$index]; $i++) {
                        $i_data = array();
                        $i_data['bid'] = $ids;
                        $i_data['xuhao'] = $i + 1;
                        Db::name("sanren")->insert($i_data);
                    }
                } elseif ($task_num[$index] < $count) {
                    // 尝试减少条数
                    for ($i = $task_num[$index]; $i < $count; $i++) {
                        $d = Db::name("sanren")->where("bid", $ids)->order("id desc")->find();
                        if (empty($d)) {
                            continue;
                        } else {
                            if (empty($d['name'])) {
                                Db::name("sanren")->where("id", $d['id'])->delete();
                            } else {
                                continue;
                            }
                        }
                    }
                }
            }
        }
        $site = Config::get('site');
        $array2 = array_keys($site['task_list']);
        $result1 = array_values(array_diff($array2, $gai_task));
        $msg = '';

        $result = false;
        Db::startTrans();
        try {
            foreach ($result1 as $index => $item) {
                $params['task_' . $item] = 0;
                if ($item == 1) {
                    // 本车定损
                    if($row['status'] != 0){
                        $msg = $msg.'本车定损,';
                    }
                } elseif ($item == 2) {
                    // 三者财物损失定损
                    $d = Db::name("scwusun")->where("bid", $ids)->order("id desc")->select();
                    if (count($d) == 0) {
                        continue;
                    } else {
                        $i = 0;
                        foreach ($d as &$v){
                            if($v['status'] != 0){
                                $msg = $msg.'三者财物损失,';
                                $i = 1;
                                continue;
                            }
                        }
                        if($i == 0){
                            Db::name("scwusun")->where("bid", $ids)->delete();
                        }
                    }
                } elseif ($item == 3) {
                    // 三者车损失定损
                    $d = Db::name("sanche")->where("bid", $ids)->order("id desc")->select();
                    if (count($d) == 0) {
                        continue;
                    } else {
                        $i = 0;
                        foreach ($d as &$v){
                            if($v['status'] != 0){
                                $msg = $msg.'三者车损失,';
                                $i = 1;
                                continue;
                            }
                        }
                        if($i == 0){
                            Db::name("sanche")->where("bid", $ids)->delete();
                        }
                    }
                } elseif ($item == 4) {
                    // 本车人伤
                    $d = Db::name("benren")->where("bid", $ids)->order("id desc")->select();
                    if (count($d) == 0) {
                        continue;
                    } else {
                        $i = 0;
                        foreach ($d as &$v){
                            if($v['status'] != 0){
                                $msg = $msg.'本车人伤,';
                                $i = 1;
                                continue;
                            }
                        }
                        if($i == 0){
                            Db::name("benren")->where("bid", $ids)->delete();
                        }
                    }
                } elseif ($item == 5) {
                    // 三者人伤
                    $d = Db::name("sanren")->where("bid", $ids)->order("id desc")->select();
                    if (count($d) == 0) {
                        continue;
                    } else {
                        $i = 0;
                        foreach ($d as &$v){
                            if($v['status'] != 0){
                                $msg = $msg.'三者人伤,';
                                $i = 1;
                                continue;
                            }
                        }
                        if($i == 0){
                            Db::name("sanren")->where("bid", $ids)->delete();
                        }
                    }
                }
            }
            $msg = rtrim($msg, ",");
            if($msg){
                Db::rollback();
                return $this->error('请先将'.$msg.'退回到查勘状态');
            }
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::name('diaodu_log')->insert($log);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 查勘机构与查勘人
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function jigou()
    {
        $where = $_POST;
        $data = Db::name('zuzhi')->where('delete_id', 0)->select();
        //出理上下级关系
        $arr = getSubs1($data, $where['chakan_group']);
        $arr[] = $where['chakan_group'];
//        $ren = Db::name('admin')->whereIn('zuzhi', $arr)->field('id,username,mobile')->select();
        $ren = Db::name('admin')->alias('a')->whereIn('a.zuzhi', $arr)->join('auth_group_access b','a.id = b.uid')->where('b.group_id',10)->field('a.id,a.username,a.mobile')->select();
        $this->success('', '', $ren);
    }

    /**
     * 查勘人手机号
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function jigou_ren()
    {
        $data = $_POST;
        $mobile = Db::name('admin')->where($data)->value('mobile');
        $this->success('', '', $mobile);
    }

    /**
     * 调度记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function diaodu_log()
    {
        $id = $this->request->post("id", 0, "intval");
        $bid = $this->request->post("bid", 0, "intval");
        if (empty($id) || empty($bid)) $this->error('参数不存在');
        $log = Db::name('diaodu_log')->field('task,task_num')->where('bid', $bid)->where("chakan_user_id", $id)->order('id desc')->find();
        if (empty($log)) $this->error('数据不存在');
        $this->success('', '', $log);
    }


}
